import sys

import json

from blspy import AugSchemeMPL, G1Element, G2Element, PrivateKey

from chia.types.condition_opcodes import ConditionOpcode

from chia.util.hash import std_hash

from clvm.casts import int_to_bytes

from functools import reduce

from chia.types.blockchain_format.program import Program

from chia.wallet.puzzles.p2_delegated_puzzle_or_hidden_puzzle import (  # standard_transaction
    puzzle_for_pk,
    calculate_synthetic_secret_key,
    DEFAULT_HIDDEN_PUZZLE_HASH,
)

from chia.consensus.default_constants import DEFAULT_CONSTANTS

from typing import Dict, List, Tuple, Optional, Union


# Converts a hexadecimal string in an array to bytes
def convertConditions(arrs):
    for i in range(0, len(arrs)): 
        ob=arrs[i]
        if isinstance(ob,list):
            convertConditions(ob)
        elif isinstance(ob,str) and ob.index("0x") == 0:
            arrs[i]=bytes.fromhex(ob[2:])


def sign_standard_spend(coinName: bytes,priv: PrivateKey, conditions: List[List]):
    delegated_puzzle_solution = Program.to((1, conditions))
    solution = Program.to([[], delegated_puzzle_solution, []])

    return solution,AugSchemeMPL.sign(
        calculate_synthetic_secret_key(priv, DEFAULT_HIDDEN_PUZZLE_HASH),
        (delegated_puzzle_solution.get_tree_hash() + coinName + DEFAULT_CONSTANTS.AGG_SIG_ME_ADDITIONAL_DATA),
    )


data=json.loads(sys.argv[1])

#secret key
SK=PrivateKey.from_bytes(bytes.fromhex(data["sk"][2:]))

#public key
PK=SK.get_g1()

#programe
puzzlePrograme=puzzle_for_pk(PK)

#coin id
CoinName= bytes.fromhex(data["id"][2:])

#conditions
condition_args: List[List] = data["args"]

convertConditions(condition_args)

solution,signature=sign_standard_spend(CoinName,SK,condition_args)

output={'puzzle_reveal':str(puzzlePrograme),'solution':str(solution),'signature':str(signature)}

print(json.dumps(output))

